package com.mf.controller.admin;

import com.mf.entity.GoodsMold;
import com.mf.entity.Log;
import com.mf.service.GoodsMoldService;
import com.mf.service.LogService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SKU 商品类型
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/admin/goodsmold")
public class GoodsMoldController {

    @Resource
    private GoodsMoldService goodsMoldService;

    @Resource
    private LogService logService;

    /*
    *
    *
    * */
    @RequestMapping("/list")
    @RequiresPermissions(value = {"商品类型", "商品规格"}, logical = Logical.OR)
    public Map<String, Object> getGoodsTypeList(GoodsMold goodsMold, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "rows", required = false) Integer rows) throws Exception{
        Map<String, Object> result = new HashMap<>();
        List<GoodsMold> goodsMoldList = goodsMoldService.list(goodsMold, page, rows, Sort.Direction.ASC, "id");
        Long goodsMoldCount = goodsMoldService.getCount(goodsMold);
        result.put("rows", goodsMoldList);
        result.put("total", goodsMoldCount);
        logService.save(new Log(Log.SEARCH_ACTION, "查询SKU商品类型信息"));
        return result;
    }


    @GetMapping("/all")
    public List<GoodsMold> getAllGoodsTypes(){
        return goodsMoldService.all();
    }


    /*
    * 添加或者修改sku商品类型
    *
    * @return
    * @param
    * */
    @RequestMapping("/save")
    public Map<String, Object> save(GoodsMold goodsMold) throws Exception{
        Map<String, Object> result = new HashMap<>();

        if(goodsMold.getId() != null){
            logService.save(new Log(Log.UPDATE_ACTION, "更新sku商品类型" + goodsMold));
        }else{
            logService.save(new Log(Log.ADD_ACTION, "添加sku商品类型" + goodsMold));
        }
        goodsMoldService.save(goodsMold);
        result.put("success", true);
        return result;
    }


    /*
    * 删除sku商品类型
    * */
    @RequestMapping("/delete")
    public Map<String, Object> deleteGoodsMold(String ids) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        String[] idsStr = ids.split(",");
        for (int i = 0; i < idsStr.length; i++) {
            int id = Integer.parseInt(idsStr[i]);
            logService.save(new Log(Log.UPDATE_ACTION, "删除sku商品类型 id:" + id));
            goodsMoldService.delete(id);
        }
        resultMap.put("success", true);
        return resultMap;
    }


}
